<template>
  <view class="search-page">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <input class="search-input" v-model="keyword" placeholder="点击搜索商品" @confirm="onSearch" />
      <button class="search-btn" @click="onSearch">搜索</button>
    </view>
    <!-- 搜索历史 -->
    <view class="history-title" v-if="searchHistory.length">
      搜索历史
      <text class="clear-btn" @click.stop="clearHistory">清空</text>
    </view>
    <view class="history-tags" v-if="searchHistory.length">
      <view class="tag" v-for="(item, idx) in searchHistory" :key="idx" @click="onHistoryClick(item)">{{ item }}</view>
    </view>
    <!-- 热门搜索 -->
    <view class="hot-search-title">热门搜索</view>
    <view class="hot-search-tags">
      <view class="tag" v-for="(item, idx) in hotTags" :key="idx" @click="onHotTagClick(item)">{{ item }}</view>
    </view>
    <view class="divider"><text>热门推荐</text></view>
    <!-- 商品推荐列表 -->
    <view class="goods-list">
      <view class="goods-row" v-for="(row, rowIdx) in goodsRows" :key="rowIdx">
        <view class="goods-card" v-for="(item, idx) in row" :key="idx" @click="goToDetail(item.id)">
          <image :src="item.img" class="goods-img" />
          <view class="goods-info">
            <view class="goods-tags">
              <text v-for="(tag, tIdx) in item.tags" :key="tIdx" :class="'goods-tag ' + tag.type">{{ tag.text }}</text>
            </view>
            <view class="goods-title">{{ item.title }}</view>
            <view class="goods-desc">{{ item.desc }}</view>
            <view class="goods-bottom">
              <view class="goods-price-line">
                <text class="price">￥{{ item.price }}</text>
              </view>
              <button class="buy-btn">立即抢</button>
            </view>
          </view>
        </view>
      </view>
      <!-- 加载中和无更多提示 -->
      <view v-if="loading" class="loading-text">加载中...</view>
      <view v-if="finished" class="finished-text">没有更多了</view>
    </view>
  </view>
</template>

<script>
import { list } from '@/api/index'
import { getUserHistory,putUserHistory } from '@/api/login'
export default {
  name: 'SearchPage',
  data() {
    return {
      goodsList: [],
      loading: false,
      finished: false,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      searchHistory: [],
      keyword: '',
      isLogin: false, // 新增：登录状态
      hotTags: ['衣服', '香水', '鞋子']
    }
  },
  computed: {
    goodsRows() {
      // 将商品列表每两个分为一组，用于一行显示两个商品
      const rows = []
      for (let i = 0; i < this.goodsList.length; i += 2) {
        rows.push(this.goodsList.slice(i, i + 2))
      }
      return rows
    }
  },
  onLoad() {
    this.isLogin = !!uni.getStorageSync('token');
    this.pageNum = 1;
    this.finished = false;
    if (this.isLogin) {
      this.syncLocalHistoryToServer().then(() => {
        this.getHistoryFromServer();
      });
    } else {
      this.getHistoryFromLocal();
    }
    this.searchGoods();
  },
  onReachBottom() {
    this.loadMoreGoods();
  },
  methods: {
    async searchGoods(isLoadMore = false) {
      if (this.loading || this.finished) return;
      this.loading = true;
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          keyword: this.keyword
        };
        const res = await list(params);
        const records = res.rows || [];
        const newGoods = records.map(item => ({
          img: item.imgUrl,
          title: item.goodsName,
          desc: item.introduce,
          price: item.price,
          originPrice: item.originPrice || '',
          sales: item.sales || 0, // 新增销量字段
          tags: item.tagName
            ? item.tagName.split(',').map(tag => ({ text: tag, type: 'green' }))
            : [],
          id: item.id
        }));
        if (isLoadMore) {
          this.goodsList = this.goodsList.concat(newGoods);
        } else {
          this.goodsList = newGoods;
        }
        this.total = res.total || 0;
        if (this.goodsList.length >= this.total) {
          this.finished = true;
        } else {
          this.pageNum++;
        }
      } catch (e) {}
      this.loading = false;
    },
    loadMoreGoods() {
      this.searchGoods(true);
    },
    async syncLocalHistoryToServer() {
      const localHistory = uni.getStorageSync('search_history') || [];
      if (localHistory.length) {
        await putUserHistory(localHistory.join(','));
        uni.removeStorageSync('search_history');
      }
    },
    getHistoryFromLocal() {
      this.searchHistory = uni.getStorageSync('search_history') || [];
    },
    async getHistoryFromServer() {
      const res = await getUserHistory();
      this.searchHistory = res.data ? res.data.split(',').filter(Boolean) : [];
    },
    async saveHistory(keyword) {
      if (this.isLogin) {
        let history = this.searchHistory.filter(item => item !== keyword);
        history.unshift(keyword);
        if (history.length > 10) history = history.slice(0, 10);
        await putUserHistory(history.join(','));
        this.searchHistory = history;
      } else {
        let history = uni.getStorageSync('search_history') || [];
        history = history.filter(item => item !== keyword);
        history.unshift(keyword);
        if (history.length > 10) history = history.slice(0, 10);
        uni.setStorageSync('search_history', history);
        this.searchHistory = history;
      }
    },
    async clearHistory() {
      if (this.isLogin) {
        await putUserHistory('');
        this.searchHistory = [];
      } else {
        uni.removeStorageSync('search_history');
        this.searchHistory = [];
      }
    },
    onHistoryClick(keyword) {
      this.keyword = keyword;
      this.saveHistory(keyword);
      uni.navigateTo({
        url: `/pages/search/result?keyword=${encodeURIComponent(keyword)}`
      });
    },
    onHotTagClick(keyword) {
      this.keyword = keyword;
      this.saveHistory(keyword);
      uni.navigateTo({
        url: `/pages/search/result?keyword=${encodeURIComponent(keyword)}`
      });
    },
    onSearch() {
      if (!this.keyword) return;
      this.saveHistory(this.keyword);
      uni.navigateTo({
        url: `/pages/search/result?keyword=${encodeURIComponent(this.keyword)}`
      });
    },
    goToDetail(id) {
      uni.navigateTo({ url: `/pages/product/detail?id=${id}` });
    }
  }
}
</script>

<style scoped>
.search-page {
  background: #fff;
  min-height: 100vh;
  padding-bottom: 20px;
}
.search-bar {
  display: flex;
  align-items: center;
  padding: 16px 12px 8px 12px;
  background: #fff;
  border-bottom: 1px solid #f2f2f2;
}
.search-input {
  flex: 1;
  height: 32px;
  border: none;
  border-radius: 16px;
  padding: 0 12px;
  background: #f7f7f7;
  font-size: 14px;
  margin-right: 8px;
}
.search-btn {
  background: #fff;
  color: #222;
  border: none;
  border-radius: 16px;
  padding: 0 16px;
  height: 32px;
  font-size: 14px;
  border: 1px solid #eee;
}
.hot-search-title {
  font-size: 16px;
  font-weight: bold;
  margin: 18px 0 8px 16px;
}
.hot-search-tags {
  display: flex;
  gap: 12px;
  margin-left: 16px;
  margin-bottom: 10px;
}
.tag {
  background: #f7f7f7;
  color: #222;
  border-radius: 16px;
  padding: 4px 16px;
  font-size: 14px;
}
.divider {
  display: flex;
  align-items: center;
  margin: 18px 0 12px 0;
  color: #888;
  font-size: 15px;
}
.divider:before, .divider:after {
  content: '';
  flex: 1;
  height: 1px;
  background: #eee;
  margin: 0 12px;
}
/* 商品列表样式已移至全局样式文件 */
.history-title {
  font-size: 15px;
  font-weight: bold;
  margin: 18px 0 8px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.clear-btn {
  color: #ff6700;
  font-size: 13px;
  margin-left: 12px;
}
.history-tags {
  display: flex;
  gap: 12px;
  margin-left: 16px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}
</style> 